// pages/screens/add/add.js
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
const util = require('../../../utils/util.js');
const jsonData = require("../jsondata.js");
const screenservice = require("../../../apiservice/screen/screenservice");
const schoolservice = require("../../../apiservice/school/schoolservice");
const screenteamservice = require("../../../apiservice/screen/screenteamservice");
const screenitemservice = require("../../../apiservice/screen/screenitemservice");
const screentemplateservice = require("../../../apiservice/screen/screentemplateservice");

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		entrytype: 'add', //进入页面是添加还是赋值
		screenTypeIndex: 0,
		singleModeIndx: 0,
		singleModeIsChecked: true,
		teamModeIndex: 1,
		teamModeIndexIsChecked: false,
		screenGroupIndex: 0,
		screenItemIndex: 0,
		screenTemplateIndex: 0,
		checkscreenResources: [],
		screenResources: jsonData.screenResources,
		dbsChecked: false,
		lxdChecked: false,
		xccChecked: false,
		scChecked: false,
		dxChecked: false,
		scChecked: false,
		dateStartShow: false,
		dateEndShow: false,
		endminDate: util.addDate(new Date().getTime(), "Year", 0),
		minDate: util.addDate(new Date().getTime(), "Year", 0),
		maxDate: new Date(new Date().getFullYear() + 1, 11, 31, 23, 59, 59).getTime(),
		startDate: util.getDefaultDate(new Date(util.addDate(new Date().getTime(), "day", 1)), 8, 0, 0),
		endDate: util.getDefaultDate(new Date(util.addDate(new Date().getTime(), "day", 1)), 17, 0, 0),
		currStartDate: new Date(util.getDefaultDate(new Date(util.addDate(new Date().getTime(), "day", 1)), 8, 0, 0)).getTime(),
		currEndDate: new Date(util.getDefaultDate(new Date(util.addDate(new Date().getTime(), "day", 1)), 17, 0, 0)).getTime(),
		screenTypeData: jsonData.screenType,
		screenTypeIndex: 0,
		screenTypeName: "社区筛查",
		communityId: null,
		communityName: "请选择",
		schoolId: null,
		schoolName: "请选择",
		systemUserId: "",
		systemUserName: "",
		screenTeamData: {},
		screenTeamIndex: 0,
		screenTeamName: "请选择",

		screenItemData: {},
		screenItemIndex: 0,
		screenItemName: "请选择",

		screenTemplateData: {},
		screenTemplateIndex: 0,
		screenTemplateName: "请选择",

		outreachValue: "",
		preachValue: "",
		thedriverValue: "",
		screeningdoctorValue: "",
		screeningnurseValue: "",
		otherValue: "",

		EntryModeIndex: 0,

		SaveDisabled: false,

		screenCrewDisplay: false,

		region: ['湖南省', '长沙市', '天心区'],
	},
	
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function(options) {

		var that = this;
		let screenresources = await jsonData.initScreenResources();
		//debugger;
		this.setData({
			screenResources: screenresources
		})
		
		await this.GetScreenTeamData(app.globalData.userInfo.userid);
		//debugger;
		this.setData({
			screenTeamIndex: 0,
			screenTeamName: this.data.screenTeamData[0].new_name,
		});
		await this.GetScreenItemData(app.globalData.userInfo.siteid);
		await this.GetScreenTemplateData();
		this.setData({
			systemUserId: app.globalData.userInfo.userid,
			systemUserName: app.globalData.userInfo.fullname
		});
	
		const eventChannel = this.getOpenerEventChannel()
		// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
		eventChannel.on('OpenScreenAddPage', function(res) {
			console.log(res.data)
			wx.showLoading({
				title: '加载中...',
				mask: true,
			})
			//赋值
			that.assignmentValue(res.data);
			wx.hideLoading();
		})
	
	},
	
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		let userInfo = getApp().globalData.userInfo;
	
		//默认用户医院的省市县
		if (userInfo && !this.data.schoolId) {
			var region = [];
			this.setData({
				userid: userInfo.userid
			});
			region.push(userInfo.new_provincename);
			region.push(userInfo.new_cityname);
			if (userInfo.new_areaname) {
				region.push(userInfo.new_areaname);
			} else {
				region.push('');
			}
			this.setData({
				region: region
			})
		}
	},

	//创建筛查信息
	async CreateScreenData(screenState) {
		try {
			var that = this.data;
			var screenData = {};
			if (screenState == 0) {
				screenData.new_screenstate = screenState;
			} else if (screenState == 1) {
				screenData.new_screenstate = screenState;
			}

			//debugger;
			screenData.new_screentype = that.screenTypeData[that.screenTypeIndex].id;
			if (that.screenTypeIndex == 0) {
				screenData.new_communityId = that.communityId;
			} else if (that.screenTypeIndex == 1) {
				screenData.new_schoolId = that.schoolId;
			}
			//录入模式
			screenData.new_templatetype = jsonData.screenEntryMode[that.EntryModeIndex].id;

			screenData.new_startdate = that.startDate;
			screenData.new_enddate = that.endDate;
			screenData.OwnerId = that.systemUserId;
			if (that.screenTeamData && that.screenTeamData.length > 0) {
				screenData.new_screenteamId = that.screenTeamData[that.screenTeamIndex].new_screenteamId;
			}
			if (that.screenItemData && that.screenItemData.length > 0) {
				screenData.new_new_screenitem = that.screenItemData[that.screenItemIndex].new_screenitemId;
			}
			if (that.screenTemplateData && that.screenTemplateData.length > 0) {
				screenData.new_checkmenu = that.screenTemplateData[that.screenTemplateIndex].templateId;
			}

			screenData.new_outreach = this.data.outreachValue;
			screenData.new_preach = this.data.preachValue;
			screenData.new_thedriver = this.data.thedriverValue;
			screenData.new_screeningdoctor = this.data.screeningdoctorValue;
			screenData.new_screeningnurse = this.data.screeningnurseValue;
			screenData.new_other = this.data.otherValue;
          
			screenData.Resources = that.checkscreenResources;
			var result = await screenservice.CreateScreenData(screenData);
			console.log(result);
			if (result.data.result && result.data.resultMes == "成功") {

				this.JumpPage();
			}
			// 
		} catch (e) {
			console.log(e);
		} finally {
			this.setData({
				SaveDisabled: false,
			});
			wx.hideLoading();
		}
	},

	//赋值
	assignmentValue: function(screenDetail) {
		//文本赋值
		this.setData({
			entrytype: 'copy',
			systemUserName: screenDetail.ownerFullName,

		});
		//选项集赋值
		var tmplateindex = this.data.screenTemplateData.findIndex(function(item, index) {
			return item.templateId == screenDetail.new_checkmenu
		})
		var screenItemindex = this.data.screenItemData.findIndex(function(item, index) {
			return item.new_screenitemId == screenDetail.new_new_screenitem
		})
		var screenTeamindex = this.data.screenTeamData.findIndex(function(item, index) {
			return item.new_screenteamId == screenDetail.new_screenteamId
		})

		if (tmplateindex != -1) {
			this.setData({
				screenTemplateIndex: tmplateindex,
				screenTemplateName: screenDetail.new_checkmenuName,
			})
		}

		if (screenTeamindex != -1) {
			this.setData({
				screenTeamIndex: screenTeamindex,
				screenTeamName: screenDetail.new_screenteamName,
			})
		}


		if (screenDetail.new_new_screenitemName) {
			this.setData({
				screenItemName: screenDetail.new_new_screenitemName,
				screenItemIndex: screenItemindex,
			})
		}

		if (screenDetail.new_templatetype == 1) {
			this.setData({
				EntryModeIndex: 1,
			});
		} else if (screenDetail.new_templatetype == 2) {
			this.setData({
				EntryModeIndex: 0,
			});
		}

		if (screenDetail.new_screentype == 100000000) {
			//社区
			this.setData({
				screenTypeIndex: 0,
				screenTypeName: this.data.screenTypeData[0].name,
				communityName: screenDetail.new_communityName,
				communityId: screenDetail.new_communityId,
			});
		} else if (screenDetail.new_screentype == 100000002 || screenDetail.new_screentype == 100000001) {

			//校园
			this.setData({
				screenTypeIndex: 1,
				screenTypeName: this.data.screenTypeData[1].name,
				schoolName: screenDetail.new_schoolName,
				schoolId: screenDetail.new_schoolId,
			});
		}

		if (screenDetail.equipList != null && screenDetail.equipList.length != 0) {
			var eList = [];
			screenDetail.equipList.forEach(element => {
				var checkboxindex = this.data.screenResources.findIndex(function(item, index) {
					return item.name === element.new_name
				})
				eList.push((checkboxindex + 1) + "");

			});
			this.setData({
				checkscreenResources: eList
			})
		}

		//筛查人员信息
		if (screenDetail.new_outreach) {
			this.setData({
				outreachValue: screenDetail.new_outreach,
			})
		}
		if (screenDetail.new_preach) {
			this.setData({
				preachValue: screenDetail.new_preach,
			})
		}
		if (screenDetail.new_thedriver) {
			this.setData({
				thedriverValue: screenDetail.new_thedriver,
			})
		}
		if (screenDetail.new_screeningdoctor) {
			this.setData({
				screeningdoctorValue: screenDetail.new_screeningdoctor,
			})
		}
		if (screenDetail.new_screeningnurse) {
			this.setData({
				screeningnurseValue: screenDetail.new_screeningnurse,
			})
		}
		if (screenDetail.new_other) {
			this.setData({
				otherValue: screenDetail.new_other,
			})
		}

	},

	//筛查类型change时
	changeScreenType: async function(e) {
		console.log(e);
		var index = e.detail.value;
		this.setData({
			screenTypeIndex: index,
			screenTypeName: this.data.screenTypeData[index].name
		});
		//选择为校园筛查时只能选择团队模式
		if (this.data.screenTypeData[index].id == 100000001) {
			this.setData({
				EntryModeIndex: 1
			});
		}
	},

	//选择社区
	selectCommunity(e) {
		var that = this;
		var url = "../../community/list/list";
		if (this.data.screenTypeIndex == 0) {
			if (that.data.communityId != null) {
				url += "?communityId=" + that.data.communityId;
			}
		}
		wx.navigateTo({
			url: url,
			events: {
				openedCommunityPage: function(e) {
					console.log(e.data)
				},
				communityEvent: function(data) {
					console.log(data)
					that.setData({
						communityId: data.communityId,
						communityName: data.communityName
					});
				}
			},
			success: function(res) {
				res.eventChannel.emit('openedCommunityPage', {
					data: 'choose'
				})
			}
		})
	},

	//选择学校
	selectSchool(e) {
		var that = this;
		//debugger;
		let province = this.data.region[0];
		let city = this.data.region[1];
		let area = this.data.region[2];

		let toUrl = `../../school/list/list?`
		if (province && city && area) {
			toUrl += `province=${province}&city=${city}&area=${area}`;
		}
		wx.navigateTo({
			url: toUrl,
			events: {
				openedSchoolPage: function(e) {
					console.log(e.data)
				},
				schoolEvent: function(data) {
					that.GetSchoolData(that, data.schoolId);
					//console.log(data)
					that.setData({
						schoolId: data.schoolId,
						schoolName: data.schoolName
					});
				}
			},
			success: function(res) {
				console.log(that.region);
				res.eventChannel.emit('openedSchoolPage', {
					data: 'choose'
				});

				if (that.data.schoolId) {
					// res.eventChannel.emit('schoolEvent', {
					// 	data: that.data.region
					// });
				}

			}
		})
	},

	//显示开始时间
	selectStratDate() {
		this.setData({
			dateStartShow: true
		})
	},

	//关闭开始时间并进行赋值
	onStartConfirm(e) {
		var time = e.detail;
		var enddate = util.getDefaultDate(new Date(time), 17, 0, 0);

		//debugger;
		//console.log(enddate)

		this.setData({
			dateStartShow: false,
			startDate: util.formatTime(new Date(time)),
			currStartDate: time,
			currEndDate: new Date(enddate).getTime(),
			endDate: enddate,
			//currEndDate: new Date(enddate)
		})
	},

	//关闭开始时间
	onStartCancel(e) {
		this.setData({
			dateStartShow: false
		})
	},

	//显示结束时间
	selectEndDate() {
		this.setData({
			dateEndShow: true
		})
	},

	//关闭结束时间并进行赋值
	onEndConfirm(e) {
		var time = e.detail;
		this.setData({
			dateEndShow: false,
			endDate: util.formatTime(new Date(time)),
			currEndDate: new Date(util.formatTime(new Date(time)))
		})
	},

	//关闭结束时间
	onEndCancel(e) {
		this.setData({
			dateEndShow: false
		})
	},

	

	//根据学校Id获取该省市区
	async GetSchoolData(that, schoolId) {
		try {
			if (schoolId) {
				var schoolData = await schoolservice.getSchoolDetail(schoolId);
				if (schoolData != null) {
					var provinceName = '';
					var cityName = '';
					var areaName = '';
					if (schoolData.data.new_provinceName != null) {
						provinceName = schoolData.data.new_provinceName;
					}
					if (schoolData.data.new_cityName != null) {
						cityName = schoolData.data.new_cityName;
					}
					if (schoolData.data.new_areaName != null) {
						areaName = schoolData.data.new_areaName;
					}
					that.setData({
						region: [provinceName, cityName, areaName]
					});
				}
				console.log(schoolData.data);
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//根据当前用户获取到筛查小组
	async GetScreenTeamData(userId) {
		try {
			if (userId) {
				var screenTeamInfo = await screenteamservice.GetScreenTeamByOwnerId(userId);
				console.log(screenTeamInfo.data);
				if (screenTeamInfo) {
					this.setData({
						screenTeamData: screenTeamInfo.data,
					});
				}
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//根据医院获取筛查项目
	async GetScreenItemData(hospitalId) {
		try {
			if (hospitalId) {
				var screenItemInfo = await screenitemservice.GetScreenItemData(hospitalId);
				console.log(screenItemInfo.data);
				if (screenItemInfo) {
					this.setData({
						screenItemData: screenItemInfo.data,
					});
				}
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//获取所有筛查模板
	async GetScreenTemplateData() {
		try {
			let screenTemplateInfo = await screentemplateservice.GetScreenTemplateData();
			
			//console.log(screenTemplateInfo.data);
			if (screenTemplateInfo) {
				this.setData({
					screenTemplateData: screenTemplateInfo.data,
				});
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//筛查小组change时
	changeScreenTeam: async function(e) {
		console.log(e);
		if (this.data.screenTeamData && this.data.screenTeamData.length > 0) {
			var screenTeamName = this.data.screenTeamData[e.detail.value].new_name;
			this.setData({
				screenTeamIndex: e.detail.value,
				screenTeamName: screenTeamName
			});
		}
	},

	//筛查小组change时
	changeScreenItem: async function(e) {
		console.log(e);
		if (this.data.screenItemData && this.data.screenItemData.length > 0) {
			var screenItemName = this.data.screenItemData[e.detail.value].new_name;
			this.setData({
				screenItemIndex: e.detail.value,
				screenItemName: screenItemName
			});
		}
	},

	//筛查模板change时
	changeScreenTemplate: async function(e) {
		console.log(e);
		if (this.data.screenTemplateData && this.data.screenTemplateData.length > 0) {
			var screenTemplateName = this.data.screenTemplateData[e.detail.value].templateName;
			this.setData({
				screenTemplateIndex: e.detail.value,
				screenTemplateName: screenTemplateName
			});
		}
	},

	//保存
	onSave: async function(e) {

		if (this.data.communityId == null && this.data.screenTypeIndex == 0) {
			this.shouTips("请选择社区");
			return;
		}
		if (this.data.schoolId == null && this.data.screenTypeIndex == 1) {
			this.shouTips("请选择学校");
			return;
		}
		if (this.data.screenTeamName == '请选择') {
			this.shouTips("请选择筛查小组");
			return;
		}
		if (this.data.endDate <= this.data.startDate) {
			this.shouTips("结束时间必须大于开始时间");
			return;
		}
		if (this.data.screenTemplateName == '请选择') {
			this.shouTips("请选择项目模板");
			return;
		}

		var currentUserRole = app.globalData.userInfo.mobilerole_systemuser;
		var reg = RegExp(/2/);
		if (this.checkRequireAttribute()) {
			if (reg.exec(currentUserRole)) {
				this.setData({
					SaveDisabled: true,
				});
				wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
					title: '加载中',
					icon: 'loading'
				});
				await this.CreateScreenData(0);
			}
		}
	},

	//保存并发布
	onSavePublish: async function(e) {
		if (this.data.communityId == null && this.data.screenTypeIndex == 0) {
			this.shouTips("请选择社区");
			return;
		}
		if (this.data.schoolId == null && this.data.screenTypeIndex == 1) {
			this.shouTips("请选择学校");
			return;
		}
		if (this.data.screenTeamName == '请选择') {
			this.shouTips("请选择筛查小组");
			return;
		}
		if (this.data.endDate <= this.data.startDate) {
			this.shouTips("结束时间必须大于开始时间");
			return;
		}
		if (this.data.screenTemplateName == '请选择') {
			this.shouTips("请选择项目模板");
			return;
		}

		var currentUserRole = app.globalData.userInfo.mobilerole_systemuser;
		var reg = RegExp(/2/);
		if (reg.exec(currentUserRole)) {
			this.setData({
				SaveDisabled: true,
			});
			wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
				title: '加载中',
				icon: 'loading'
			});
			await this.CreateScreenData(1);
		}


	},

	JumpPage() {
		wx.switchTab({
			url: "../list/list",
			success: function(e) {
				var page = getCurrentPages().pop();
				if (!page) return;
				page.switchStateScreenCallBack(1);
			}
		});
	},

	//提交时检查必填字段
	checkRequireAttribute: function() {
		if (this.data.screenTypeIndex == 0) {
			if (this.data.communityName == "请选择") {
				wx.showToast({
					title: '请选择社区',
					icon: 'none'
				})
				return false;
			}
		} else if (this.data.screenTypeIndex == 1) {
			if (this.data.schoolName == "请选择") {
				wx.showToast({
					title: '请选择学校',
					icon: 'none'
				})
				return false;
			}
		}

		if (this.data.screenTeamName == "请选择") {
			wx.showToast({
				title: '请选择筛查小组',
				icon: 'none'
			})
			return false;
		}

		if (this.data.screenTemplateName == "请选择") {
			wx.showToast({
				title: '请选择项目模板',
				icon: 'none'
			})
			return false;
		}
		return true;
	},
	//外联改变时 获取值
	ChangeOutreach: function(e) {
		this.setData({
			outreachValue: e.detail
		});
	},

	//宣讲改变时 获取值
	ChangePreach: function(e) {
		this.setData({
			preachValue: e.detail
		});
	},

	//司机改变时 获取值
	ChangeThedriver: function(e) {
		this.setData({
			thedriverValue: e.detail
		});
	},

	//筛查医生改变时 获取值
	ChangeScreeningdoctor: function(e) {
		this.setData({
			screeningdoctorValue: e.detail
		});
	},

	//筛查护士改变时 获取值
	ChangeScreeningnurse: function(e) {
		this.setData({
			screeningnurseValue: e.detail
		});
	},

	//其他改变时 获取值
	ChangeOther: function(e) {
		this.setData({
			otherValue: e.detail
		});
	},
	//录入模式change时
	onEntryModeChange: function(event) {
		// console.log(event);
		// var data=jsonData.screenEntryMode[event.detail.index].id;
		// console.log(data);
		this.setData({
			EntryModeIndex: event.detail.index,
		});
	},
	//筛查资源选中时
	onScreenResourceChange: function(event) {
		this.setData({
			checkscreenResources: event.detail
		});
	},
	//控制筛查人员信息板块的显示
	screenCrewInfoClick: function() {
		var screenCrewDisplay = this.data.screenCrewDisplay;
		var isOpen = this.data.isOpen;
		if (screenCrewDisplay) {
			this.setData({
				openName: '筛查人员信息'
			})
		} else {
			this.setData({
				openName: '收起'
			})
		}
		this.setData({
			screenCrewDisplay: !screenCrewDisplay,
			isOpen: !isOpen,
		})

	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	radioChange: function() {},


	communityChange: function(e) {
		this.setData({
			communityIndex: e.detail.value,
		})
	},
	schoolChange: function(e) {
		this.setData({
			schoolIndex: e.detail.value,
		})
	},
	screenItemChange: function(e) {
		this.setData({
			screenItemIndex: e.detail.value
		})

	},
	screenTemplateChange: function(e) {
		this.setData({
			screenTemplateIndex: e.detail.value
		})
	},
	screenGroupChange: function(e) {
		this.setData({
			screenGroupIndex: e.detail.value
		})
	},

	dbsChange: function(e) {
		this.setData({
			dbsChecked: !!e.detail.value.length
		});
	},
	lxdChange: function(e) {
		this.setData({
			lxdChecked: !!e.detail.value.length
		});
	},
	xccChange: function(e) {
		this.setData({
			xccChecked: !!e.detail.value.length
		});
	},
	dxChange: function(e) {
		this.setData({
			dxChecked: !!e.detail.value.length
		});
	},
	scChange: function(e) {
		this.setData({
			scChecked: !!e.detail.value.length
		});
	},
	changeDate(e) {
		this.setData({
			date: e.detail.value
		});
	},
	changeTime(e) {
		this.setData({
			time: e.detail.value
		});
	},
	changeDateTime(e) {
		this.setData({
			dateTime: e.detail.value
		});
	},
	changeStartTime(e) {
		this.setData({
			startTime: e.detail.value
		});
	},
	changeEndTime(e) {
		this.setData({
			endTime: e.detail.value
		});
	},
	changeDateTimeColumn(e) {
		var arr = this.data.dateTime,
			dateArr = this.data.dateTimeArray;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		this.setData({
			dateTimeArray: dateArr,
			dateTime: arr
		});
	},
	changeStartTimeColumn(e) {
		var arr = this.data.startTime,
			dateArr = this.data.startTimeArray;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		this.setData({
			startTimeArray: dateArr,
			startTime: arr
		});
	},
	changeEndTimeColumn(e) {
		var arr = this.data.endTime,
			dateArr = this.data.endTimeArray;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		this.setData({
			endTimeArray: dateArr,
			endTime: arr
		});
	},
	//提示
	shouTips: function(tex) {
		wx.showToast({
			title: tex,
			icon: 'none',
			duration: 2000
		});
	}
})
